package com.windward.vii.service;

import com.github.pagehelper.PageHelper;
import com.windward.vii.common.JsonResult;
import com.windward.vii.common.ResultCode;
import com.windward.vii.dao.entity.AssetUserAccount;
import com.windward.vii.dao.entity.Device;
import com.windward.vii.dao.entity.User;
import com.windward.vii.dao.mapper.AssetUserAccountMapper;
import com.windward.vii.dao.mapper.DeviceMapper;
import com.windward.vii.dao.mapper.UserMapper;
import com.windward.vii.domain.user.SearchParam;
import com.windward.vii.domain.user.UserVO;
import com.windward.vii.utils.BigDecimalUtil;
import com.windward.vii.utils.StringUtils;
import com.windward.vii.utils.UserUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserService {

    @Resource
    UserMapper userMapper;
    @Resource
    UserTokenService userTokenService;
    @Resource
    AssetUserAccountMapper assetUserAccountMapper;
    @Resource
    DeviceMapper deviceMapper;

    public boolean insert(User record) {
        int res = userMapper.insertSelective(record);
        return res > 0;
    }

    public boolean deleteUserById(Long uid) {
        int res = userMapper.deleteByPrimaryKey(uid);
        return res > 0;
    }

    public JsonResult selectUserById(Long uid) {
        if(uid == null || uid <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "用户ID错误");
        }
        AssetUserAccount user = assetUserAccountMapper.selectByUid(uid);
        UserVO userVO = UserUtils.toUserVO(user);

        String answerRate = "0%";
        if(user.getAcceptTimes() > 0 && user.getConnectTimes() > 0) {
            BigDecimal rate = BigDecimalUtil.div(new BigDecimal(user.getAcceptTimes()),
                    new BigDecimal(user.getConnectTimes()));
            answerRate = BigDecimalUtil.round(BigDecimalUtil.mul(rate, new BigDecimal(100)), 0)+ "%";
        }
        userVO.setAnswerRate(answerRate);

        JsonResult jsonResult = JsonResult.success();
        jsonResult.setBody(userVO);
        return jsonResult;
    }

    public User getUserById(Long uid) {
        if(uid == null || uid <= 0) {
            return null;
        }
        return userMapper.selectByPrimaryKey(uid);
    }


    public User selectUserByMobile(String mobile) {
        return userMapper.selectByMobile(mobile);
    }

    public User selectByThirdId(String thirdId) {
        return userMapper.selectByThirdId(thirdId);
    }

    public User selectByToken(String token) {
        long uid = userTokenService.getUidByToken(token);
        if (uid <= 0) {
            return null;
        }
        return userMapper.selectByPrimaryKey(uid);
    }

    public boolean updateByPrimaryKeySelective(User user) {
        return userMapper.updateByPrimaryKeySelective(user) > 0;
    }

    public boolean insertAndGetId(User user) {
        int res = userMapper.insertSelective(user);
        return res > 0;
    }

    public List<UserVO> searchUser(SearchParam param) {
        if(StringUtils.isBlank(param.getKeyword())) {
            return new ArrayList<>();
        }
        int pageNum = param.getPageNum() == null ? 1 : param.getPageNum();
        int pageSize = param.getPageSize() == null ? 10 : param.getPageSize();
        PageHelper.startPage(pageNum, pageSize);

        List<AssetUserAccount> userAccounts;
        if(StringUtils.isNumeric(param.getKeyword())) {
            userAccounts = assetUserAccountMapper.searchUser(param);
        } else {
            userAccounts = assetUserAccountMapper.searchUserByNickname(param);
        }
        return UserUtils.toUserVO(userAccounts);
    }

    public int searchCount(SearchParam param) {
        return userMapper.searchCount(param);
    }

    public List<UserVO> getNewestUserList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AssetUserAccount> userAccounts = assetUserAccountMapper.getNewestUserList();
        return UserUtils.toUserVO(userAccounts);
    }

    public List<UserVO> getRecommendUserList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AssetUserAccount> userAccounts = assetUserAccountMapper.getRecommendUserList();
        return UserUtils.toUserVO(userAccounts);
    }

    public List<Long> getOnlineUserIds(Integer sex) {
        if(sex == null) {
            sex = 0;
        }
        return assetUserAccountMapper.getOnlineUserIds(sex);
    }

    public boolean updateOnlineStatusById(Long anchorUid, Integer onlineStatus) {
        try {
            assetUserAccountMapper.updateOnlineStatusByUid(anchorUid, onlineStatus);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public JsonResult bindDeviceToken(Long uid, String deviceId, String deviceToken) {
        try {
            User user = new User();
            user.setId(uid);
            user.setDeviceToken(deviceToken);
            userMapper.updateByPrimaryKeySelective(user);
            if(StringUtils.isNotEmpty(deviceId)) {
                Device device = deviceMapper.selectByDeviceId(deviceId);
                if(device != null) {
                    if(device.getDeviceToken() == null || !device.getDeviceToken().equals(deviceId)) {
                        Device updateDevice = new Device();
                        updateDevice.setId(device.getId());
                        updateDevice.setDeviceToken(deviceToken);
                        deviceMapper.updateByPrimaryKeySelective(updateDevice);
                    }
                }
            }
            return JsonResult.success();
        } catch (Exception e) {
            return JsonResult.error();
        }
    }
}
